<template>
  <van-button type="default" class="backTop" icon="back-top" round v-show="flag_scroll" @click="backTop">
  </van-button>
</template>

<script>
export default {
  data () {
    return {
      scrollTop: '',
      flag_scroll: false,
    }
  },

  methods: {
    // 滚动一定距离显示 “返回顶部” 图标
    handleScroll() {
      this.scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
      if (this.scrollTop > 100) {
        this.flag_scroll = true;
      } else {
        this.flag_scroll = false;
      }
    },

    // 时间版运动
    backTop() {
      var timer  = null;
      cancelAnimationFrame(timer);
      //获取当前毫秒数
      var startTime = +new Date();     
      //获取当前页面的滚动高度
      var b = document.body.scrollTop || document.documentElement.scrollTop;
      var d = 500;
      var c = b;
      timer = requestAnimationFrame(function func(){
        var t = d - Math.max(0,startTime - (+new Date()) + d);
        document.documentElement.scrollTop = document.body.scrollTop = t * (-c) / d + b;
        timer = requestAnimationFrame(func);
        if(t == d){
          cancelAnimationFrame(timer);
        }
      });
    }
  },

  // 监听滚动
  mounted() {
    window.addEventListener('scroll', this.handleScroll)  
  },
}
</script>

<style scoped>
.backTop {
  position: fixed;
  right: 1rem;
  bottom: 3rem;
  opacity: 80%;
  background-color: #eaeaea;
}

.van-button__icon {
  font-size: 2em;
  font-weight: bold;
}

.van-button--round {
  width: 3rem;
  height: 3rem;
  border-radius: 50%;
}
</style>